package com.zj.study;

import java.util.*;

/*
判断大家是否在一个朋友圈，第三个数为0表示是朋友，第三个数为1表示要输出判断关系。
 */
public class 根据信息进行朋友圈逐行判定 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1 5 0");
        list.add("1 2 0");
        list.add("2 5 1");
        list.add("2 3 0");
        list.add("1 4 1");
        list.add("3 5 1");
        isOneFriendCirculer2(list, 5);
    }

    //用并查集来判断是否师一个朋友圈
    public static void isOneFriendCirculer(List<String> parma, int len) {
        int[] parentArr = new int[len + 1];
        for (int i = 1; i < parentArr.length; i++) {
            parentArr[i] = i;
        }
        for (String sentence : parma) {
            String[] arr = sentence.split(" ");
            if ("0".equals(arr[2].trim())) {
                union(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]), parentArr);
            }
            if ("1".equals(arr[2].trim())) {
                int fa1 = findParent(Integer.parseInt(arr[0]), parentArr);
                int fa2 = findParent(Integer.parseInt(arr[1]), parentArr);
                System.out.println(fa1 == fa2);
            }
        }
    }

    public static void union(int son, int father, int[] relation) {
        int fa1 = findParent(son, relation);
        int fa2 = findParent(father, relation);
        relation[fa1] = fa2;
    }

    public static int findParent(int son, int[] relation) {
        if (relation[son] == son) {
            return son;
        }
        relation[son] = findParent(relation[son], relation);
        return relation[son];
    }

    //用保存每个人的朋友圈的方法来判断
    public static void isOneFriendCirculer2(List<String> parma, int len) {
        Map<String, Set<String>> records = new HashMap<>();
        for (String sentence : parma) {
            String[] arr = sentence.split(" ");
            if ("0".equals(arr[2].trim())) {
                Set<String> friends = records.computeIfAbsent(arr[0], key -> new HashSet<String>());
                if (friends.isEmpty()) {
                    friends = records.computeIfAbsent(arr[1], key -> new HashSet<String>());

                }
                friends.add(arr[0]);
                friends.add(arr[1]);
                records.put(arr[0], friends);
                records.put(arr[1], friends);
            }
            if ("1".equals(arr[2].trim())) {
                Set<String> friends = records.computeIfAbsent(arr[0], key -> new HashSet<String>());
                System.out.println(friends.contains(arr[1]));
            }
        }
        System.out.println(records);
    }


}
